package com.android.djlmapp.js_interface;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.webkit.JavascriptInterface;

import com.just.agentweb.AgentWeb;

import java.lang.ref.SoftReference;

/**
 * @Author wangziheng
 * @ProjectName djlm
 * @ClassName BaseJsInterface
 * @package com.android.djlmapp.jsInterface
 * @data 2018/12/24 12:25
 * @Describe js交互基类
 * @Change
 */
public class BaseJsInterface {
    /**
     * 更多功能里面的js key值
     */
    public static final String MORE_FUN_JS_SIGN_KEY = "Android";
    /**
     * 新js交互里面的key值
     */
    public static final String NEW_JS_SIGN_KEY = "android";
    /**
     * 调用js方法  通用方法 入参
     */
    public static final String CALL_METHEOD_NAME = "NativeRetuion";
    /**
     * 调用js方法 上传图片专用
     */
    public static final String CALL_METHEOD_UP_IMG_NAME = "returnIMG";
    private SoftReference<Activity> mSoftReference;
    private AbJsInterfaceCallBack mJsInterfaceCallBack;
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private AgentWeb mAgentWeb;

    /**
     * @param context
     * @param jsInterfaceCallBack 推荐使用 {{@link #BaseJsInterface(Context, AbJsInterfaceCallBack, AgentWeb)}}
     */
    @Deprecated
    private BaseJsInterface(Context context, AbJsInterfaceCallBack jsInterfaceCallBack) {
        this(context, jsInterfaceCallBack, null);
    }

    /**
     * @param context
     * @param jsInterfaceCallBack
     * @param agentWeb
     */
    public BaseJsInterface(Context context, AbJsInterfaceCallBack jsInterfaceCallBack, AgentWeb agentWeb) {
        mSoftReference = new SoftReference<>((Activity) context);
        mJsInterfaceCallBack = jsInterfaceCallBack;
        mAgentWeb = agentWeb;
    }

    public Activity getContext() {
        return mSoftReference.get();
    }

    public Handler getHandler() {
        return mHandler;
    }

    /**
     * 结束当前Activity
     */
    @JavascriptInterface
    public void NativeCloseWindow() {
        getHandler().post(() -> mJsInterfaceCallBack.finishActivityFromJs(getContext(),mAgentWeb));
    }


    /**
     * 回退界面,主要针对web内部跳转,如果没有可以回退的界面,则直接关闭Activity
     */
    @JavascriptInterface
    public void NativeGoBack() {
        getHandler().post(() -> mJsInterfaceCallBack.finishWebPageFromJs(getContext(),mAgentWeb));
    }


    /**
     * 前往加款界面
     */
    @JavascriptInterface
    public void NativeGoRecharge() {
        getHandler().post(() -> mJsInterfaceCallBack.goRechargeMoney(getContext()));
    }

    /**
     * 忘记密码
     */
    @JavascriptInterface
    public void NativeGetPayPwd(){
        getHandler().post(() -> mJsInterfaceCallBack.forgetPsw(getContext()));
    }
}
